#include "core/setup.hpp"
#include "yocto/exception.hpp"

namespace FastMD
{
	
	static inline void __get( lua_State *L, const char *name )
	{
		lua_settop(L, 0);
		lua_getglobal(L,name);
	}
	
	Real Setup::GetReal( lua_State *L, const char *name )
	{
		assert(L); assert(name);
		__get( L, name );
		if( ! lua_isnumber(L, -1) )
			throw exception("Setup::Get(%s) is not a Number",name);
		return Real(lua_tonumber(L, -1));
	}
	
	string Setup::GetString( lua_State *L, const char *name )
	{
		assert(L); assert(name);
		__get( L, name );
		if( ! lua_isstring(L, -1) )
			throw exception("Setup::Get(%s) is not a String",name);
		size_t      len=0;
		const char *txt=lua_tolstring(L, -1, &len);
		return string(txt,len);
	}
	
	
	V3D Setup:: GetV3D(  lua_State *L, const char *name )
	{
		assert(L); assert(name);
		__get( L, name );
		if( ! lua_istable(L,-1) )
			throw exception("Setup::Get(%s) is not a table",name);
		const size_t n = lua_objlen(L, -1);
		if( n != 3 )
			throw exception("Setup::GetV3D(%s) has %u!=3 items",name, unsigned(n) );
		
		V3D   ans;
		Real *v = &ans.x - 1;
		for( size_t i=1; i <= n; ++i )
		{
			lua_rawgeti(L,-1,i);
			if( !lua_isnumber(L,-1) )
			{
				throw exception("%s coord #%u is not a number", name, unsigned(i) ); 
			}
			v[i] = lua_tonumber(L, -1);
			lua_pop(L,1);
		}
		
		
		return ans;
	}
	
}

